mod flutter;
mod commit_msg;
mod file_check;

use clap::{Parser, Subcommand};
use colored::*;
use std::process::exit;

#[derive(Parser)]
#[command(name = "git-hooks-rs")]
#[command(author = "Your Name")]
#[command(version = "1.0")]
#[command(about = "高性能Git钩子工具 - 支持Flutter/Unity项目", long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// pre-commit钩子：代码格式化和静态检查
    PreCommit {
        /// 跳过代码格式化
        #[arg(long)]
        skip_format: bool,
        
        /// 跳过静态分析
        #[arg(long)]
        skip_analyze: bool,
    },
    
    /// commit-msg钩子：验证提交信息格式
    CommitMsg {
        /// 提交信息文件路径
        msg_file: String,
    },
    
    /// pre-push钩子：推送前检查
    PrePush {
        /// 跳过测试
        #[arg(long)]
        skip_test: bool,
    },
}

fn main() {
    let cli = Cli::parse();

    let result = match cli.command {
        Commands::PreCommit { skip_format, skip_analyze } => {
            run_pre_commit(skip_format, skip_analyze)
        }
        Commands::CommitMsg { msg_file } => {
            run_commit_msg(&msg_file)
        }
        Commands::PrePush { skip_test } => {
            run_pre_push(skip_test)
        }
    };

    if !result {
        exit(1);
    }
}

fn run_pre_commit(skip_format: bool, skip_analyze: bool) -> bool {
    println!("{}", "🔍 开始执行pre-commit检查...".blue().bold());
    println!();

    // 1. 检查大文件
    if !file_check::check_large_files(10) {
        return false;
    }
    println!();

    // 2. 检查禁止提交的文件
    if !file_check::check_forbidden_files() {
        return false;
    }
    println!();

    // 3. 检测项目类型并执行相应检查
    if file_check::is_flutter_project() {
        println!("{}", "📱 检测到Flutter项目".cyan());
        if !flutter::check_flutter(skip_format, skip_analyze) {
            return false;
        }
    } else {
        println!("{}", "ℹ️  未检测到Flutter项目，跳过Flutter检查".yellow());
    }

    println!();
    println!("{}", "✅ 所有pre-commit检查通过!".green().bold());
    true
}

fn run_commit_msg(msg_file: &str) -> bool {
    println!("{}", "🔍 验证提交信息格式...".blue().bold());
    
    if commit_msg::validate_commit_msg(msg_file) {
        println!("{}", "✅ 提交信息格式正确".green().bold());
        true
    } else {
        false
    }
}

fn run_pre_push(skip_test: bool) -> bool {
    println!("{}", "🔍 开始执行pre-push检查...".blue().bold());
    println!();

    if file_check::is_flutter_project() && !skip_test {
        println!("{}", "🧪 运行Flutter测试...".yellow());
        if !flutter::run_tests() {
            return false;
        }
    }

    println!();
    println!("{}", "✅ 所有pre-push检查通过!".green().bold());
    true
}
